<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="问题描述" name="question">
						<a-input v-model:value="searchFormState.question" placeholder="请输入问题描述" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="关联的SQL语句" name="sqlText">
						<a-input v-model:value="searchFormState.sqlText" placeholder="请输入关联的SQL语句" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="关联的DDL语句" name="ddlText">
						<a-input v-model:value="searchFormState.ddlText" placeholder="请输入关联的DDL语句" />
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="类型" name="dataType">
						<a-select v-model:value="searchFormState.dataType" placeholder="请选择类型" :options="dataTypeOptions" />
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="相关文档说明" name="document">
						<a-input v-model:value="searchFormState.document" placeholder="请输入相关文档说明" />
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="是否积极示例" name="isPositiveExample">
						<a-select v-model:value="searchFormState.isPositiveExample" placeholder="请选择是否积极示例" :options="isPositiveExampleOptions" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'"/>
					</a>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="showTrainModal" v-if="hasPerm('trainDataAdd')">
						<template #icon><plus-outlined /></template>
						导入数据源训练
					</a-button>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('trainDataAdd')">
						<template #icon><plus-outlined /></template>
						新增
					</a-button>
					<xn-batch-button
						v-if="hasPerm('trainDataBatchDelete')"
						buttonName="批量删除"
                        icon="DeleteOutlined"
						:selectedRowKeys="selectedRowKeys"
						@batchCallBack="deleteBatchTrainData"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'dataType'">
					{{ $TOOL.dictTypeData('traindatatype', record.dataType) }}
				</template>
				<template v-if="column.dataIndex === 'isPositiveExample'">
					{{ $TOOL.dictTypeData('status', record.isPositiveExample) }}
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('trainDataEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['trainDataEdit', 'trainDataDelete'], 'and')" />
						<a-popconfirm title="确定要删除吗？" @confirm="deleteTrainData(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('trainDataDelete')">删除</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()" />

	<!-- 训练数据对话框 -->
	<a-modal
		v-model:visible="trainModalVisible"
		title="导入数据源训练"
		@ok="handleTrainSubmit"
		:confirmLoading="trainLoading"
	>
		<a-form :model="trainForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
			<a-form-item label="数据源" required>
				<a-select v-model:value="trainForm.datasourceId" placeholder="请选择数据源">
					<a-select-option v-for="source in datasourceList" :key="source.id" :value="source.id">
						{{ source.name }}
					</a-select-option>
				</a-select>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup name="traindata">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import trainDataApi from '@/api/ai/trainDataApi'
		import aiDatasourceConfigApi from "@/api/ai/aiDatasourceConfigApi";
	import {message} from "ant-design-vue";
	import {embedDatabaseSchema} from "@/api/ai/vectordata";
	const searchFormState = ref({})
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	// 查询区域显示更多控制
	const advanced = ref(false)
	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}
	const columns = [
		{
			title: '问题描述',
			dataIndex: 'question'
		},
		{
			title: '关联的SQL语句',
			dataIndex: 'sqlText'
		},
		{
			title: '关联的DDL语句',
			dataIndex: 'ddlText'
		},
		{
			title: '类型',
			dataIndex: 'dataType'
		},
		{
			title: '相关文档说明',
			dataIndex: 'document'
		},
		{
			title: '是否积极示例',
			dataIndex: 'isPositiveExample'
		},
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['trainDataEdit', 'trainDataDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 150
		})
	}
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const loadData = (parameter) => {
		const searchFormParam = cloneDeep(searchFormState.value)
		return trainDataApi.trainDataPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 删除
	const deleteTrainData = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		trainDataApi.trainDataDelete(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchTrainData = (params) => {
		trainDataApi.trainDataDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}
	const dataTypeOptions = tool.dictList('traindatatype')
	const isPositiveExampleOptions = tool.dictList('status')

	// 训练数据相关
const trainModalVisible = ref(false)
const trainLoading = ref(false)
const trainForm = ref({
	datasourceId: undefined
})
const datasourceList = ref([])

// 显示训练对话框
const showTrainModal = async () => {
	trainModalVisible.value = true
	try {
		const response = await aiDatasourceConfigApi.aiDatasourceConfigPage()
		datasourceList.value = response.records
	} catch (error) {
		message.error('获取数据源列表失败：' + error.message)
	}
}

// 提交训练
const handleTrainSubmit = async () => {
	if (!trainForm.value.datasourceId) {
		message.warning('请选择数据源')
		return
	}

	trainLoading.value = true
	try {
		await embedDatabaseSchema({
			datasourceId: trainForm.value.datasourceId
		})
		message.success('训练数据提交成功')
		trainModalVisible.value = false
		tableRef.value.refresh(true)
	} catch (error) {
		message.error('训练数据提交失败：' + error.message)
	} finally {
		trainLoading.value = false
	}
}
</script>
